package interview.demo2;

/**
 * 二叉树： 先序遍历和中序遍历和后序遍历
 * @author
 * @create 2018-10-13 10:31
 **/
public class TreeNodeTest {

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(0);
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(4);

        treeNode.setLeftNode(treeNode1);
        treeNode.setRightNode(treeNode2);
        treeNode1.setLeftNode(treeNode3);
        treeNode1.setRightNode(treeNode4);
        //现在的模式是
        //       0
        //   1        2
        // 3    4
        System.out.print("先序遍历：");
        preTraverseTree(treeNode);//先序遍历的话，则为0 1 3 4 2
        System.out.println();
        System.out.println("--------------");
        System.out.print("中序遍历:");
        midTraverseTree(treeNode);//中序遍历的话，3 1 4 0 2
        System.out.println();
        System.out.println("--------------");
        System.out.print("后序遍历:");
        lastTraverseTree(treeNode);//后遍历的话，3 4 1 2 0


    }

    /**
     * 先序遍历
     *
     * @param rootNode
     */
    public static void preTraverseTree(TreeNode rootNode) {
        if (rootNode != null) {
            //访问根节点
            System.out.print(rootNode.getValue()+" ");
            //访问左节点
            preTraverseTree(rootNode.getLeftNode());
            //访问右节点
            preTraverseTree(rootNode.getRightNode());

        }
    }

    /**
     * 中序遍历
     * @param rootNode
     */
    public static void midTraverseTree(TreeNode rootNode) {
        if (rootNode != null) {
            //先访问左节点
            midTraverseTree(rootNode.getLeftNode());
            //在访问根节点
            System.out.print(rootNode.getValue()+" ");
            //在访问右节点
            midTraverseTree(rootNode.getRightNode());
        }
    }

    /**
     * 后序遍历
     * @param rootNode
     */
    public static void lastTraverseTree(TreeNode rootNode) {
        if (rootNode != null) {
            //先访问左节点
            lastTraverseTree(rootNode.getLeftNode());

            //在访问右节点
            lastTraverseTree(rootNode.getRightNode());

            //在访问根节点
            System.out.print(rootNode.getValue()+" ");
        }
    }
}
